<template>
  <div class="chat-container">
    <!-- 头部 -->
    <van-nav-bar title="在线客服系统" fixed placeholder safe-area-inset-top />

    <!-- 消息列表 -->
    <div class="messages-container" ref="messageContainer">
      <div
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message-wrapper', msg.type === 'send' ? 'message-right' : 'message-left']"
      >
        <div class="message-content">
          <div class="avatar">
            <img :src="msg.type === 'send' ? userAvatar : aiAvatar" :alt="msg.type" />
          </div>
          <div class="message-bubble">
            <div v-if="msg.msgType === 'text'" class="text-message">
              {{ msg.content }}
            </div>
            <div v-else-if="msg.msgType === 'image'" class="image-message">
              <img :src="msg.content" @click="previewImage(msg.content)" />
            </div>
            <div v-else-if="msg.msgType === 'file'" class="file-message">
              <van-icon name="description" class="file-icon" />
              <span class="file-name">{{ msg.fileName }}</span>
            </div>
          </div>
        </div>
        <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
        <!-- 在线客服状态 -->
        <div class="online-status">
          <div class="status1">正在为您连接客服 ...</div>
          <div class="status2">暂无客服在线 ...</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="toolbar">
        <van-icon name="smile-o" class="tool-icon" @click="showEmoji = true" />
        <van-icon name="photograph" class="tool-icon" @click="$refs.imageInput.click()" />
        <van-icon name="description" class="tool-icon" @click="$refs.fileInput.click()" />
        <van-icon name="volume-o" class="tool-icon" @click="startVoiceRecord" />
      </div>

      <div class="input-wrapper">
        <textarea
          v-model="inputMessage"
          class="message-input"
          placeholder="输入消息..."
          @keyup.enter.prevent="sendMessage"
          rows="1"
        ></textarea>
        <button class="send-button" @click="sendMessage">
          <van-icon name="send-o" />
        </button>
      </div>

      <!-- 隐藏的上传输入框 -->
      <input type="file" ref="imageInput" hidden @change="handleImageUpload" accept="image/*" />
      <input
        type="file"
        ref="fileInput"
        hidden
        @change="handleFileUpload"
        accept=".pdf,.doc,.docx,.xls,.xlsx"
      />
    </div>

    <!-- Emoji选择器 -->
    <van-popup v-model:show="showEmoji" position="bottom" round>
      <div class="emoji-panel">
        <div v-for="emoji in emojiList" :key="emoji" class="emoji-item" @click="insertEmoji(emoji)">
          {{ emoji }}
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useWebSocket } from '@/utils/useWebSocket'
import { useVoiceToText } from '@/utils/useVoiceToText'
import { formatTime } from '@/utils/dateFormat'
import { showImagePreview } from 'vant'

// 状态变量
const messages = ref<Array<any>>([])
const inputMessage = ref('')
const showEmoji = ref(false)
const messageContainer = ref<HTMLElement | null>(null)

// 头像配置
const userAvatar = '@/assets/img/paopao.jpeg'
const aiAvatar = '@/assets/img/hope.jpeg'

// WebSocket连接
const { sendMsg, receiveMsg } = useWebSocket()

// 语音转文字
const { startRecord, stopRecord, text } = useVoiceToText()

// 发送消息
const sendMessage = () => {
  const content = inputMessage.value.trim()
  if (!content) return

  const message = {
    type: 'send',
    msgType: 'text',
    content,
    timestamp: Date.now(),
  }

  messages.value.push(message)
  sendMsg(message)
  inputMessage.value = ''
  scrollToBottom()
}

// 处理图片上传
const handleImageUpload = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    })
    const data = await response.json()

    const message = {
      type: 'send',
      msgType: 'image',
      content: data.url,
      timestamp: Date.now(),
    }

    messages.value.push(message)
    sendMsg(message)
    scrollToBottom()
  } catch (error) {
    console.error('图片上传失败:', error)
  }
}

// 处理文件上传
const handleFileUpload = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    })
    const data = await response.json()

    const message = {
      type: 'send',
      msgType: 'file',
      content: data.url,
      fileName: file.name,
      timestamp: Date.now(),
    }

    messages.value.push(message)
    sendMsg(message)
    scrollToBottom()
  } catch (error) {
    console.error('文件上传失败:', error)
  }
}

// 监听语音转文字结果
watch(text, (newText) => {
  if (newText) {
    inputMessage.value = newText
  }
})

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

// 添加图片预览功能
const previewImage = (imageUrl: string) => {
  showImagePreview({
    images: [imageUrl],
    closeable: true,
    closeIconPosition: 'top-right'
  })
}
</script>

<style scoped lang="scss">
@import '@/style/chatAi.css';
</style>